const app = getApp()
import {
  workRelease,
  workType,
  userInfo,
  getPhone
} from '../../config/https'
//发布找师傅、找师傅工种、用户信息、绑定手机号

Page({

  /**
   * 页面的初始数据
   */
  data: {
    maskShow: false,
    phone: '',            //手机号
    longitude: '',        //经度
    latitude: '',         //纬度
    id: '',               //工种id
    typeWork: '',         //工种
    images: [],           //工地图片
    upArr: [],
    place: '请选择位置', //地点
  },
  getUserInfo(){
    userInfo({
      token: wx.getStorageSync('token')
    }).then(res => {
      if(res.code == 1){
        if(res.data.welcome.mobile){
          this.setData({
            maskShow: false,
            phone: res.data.welcome.mobile
          })
        }else{
          this.setData({
            maskShow: true
          })
        }
      }
    })
  },
  onClose(){
    this.setData({
      maskShow: false
    })
  },
  getPhoneNumber(e) {
    const detail = e.detail
    let that = this
    wx.login({
      success(res) {
        if (res.code) {
          getPhone({
            token: wx.getStorageSync('token'),
            code: res.code,
            encryptedData: detail.encryptedData,
            iv: detail.iv
          }).then(res => {
            app.$tip(res.msg)
            that.setData({
              maskShow: false
            })
            if(res.code == 1){
              that.setData({
                phone: res.data
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  // 找师傅工种
  getTypeWork(id) {
    workType({
      cate_id: id
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          typeWork: res.data
        })
      }
    })
  },
  // 工地位置选择
  choosePlace() {
    let that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          place: res.address,
          longitude: res.longitude, //经度
          latitude: res.latitude //纬度
        })
      },
      fail: function () {
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //授权成功之后，再调用chooseLocation选择地方
                          wx.chooseLocation({
                            success: function (res) {
                              that.setData({
                                place: res.address,
                                longitude: res.longitude, //经度
                                latitude: res.latitude //纬度
                              })
                            },
                          })
                        } else {
                          app.$tip('授权失败')
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            app.$tip('调用授权窗口失败')
          }
        })
      }
    })
  },
  // 工地图片
  upImg() {
    let that = this
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function (res) {
        if (!res.cancel) {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })
  },
  chooseWxImage(type) {
    let that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      count: 3 - that.data.images.length,
      success: function (res) {
        let imgArr = that.data.images
        res.tempFilePaths.forEach(item => {
          imgArr.push(item)
          wx.uploadFile({
            url: 'https://hsf.0791jr.com/api/Upload/upload',
            filePath: item,
            name: 'file',
            success(res) {
              let upArr = that.data.upArr
              let data = JSON.parse(res.data)
              if (data.code == 1) {
                upArr.push(data.data)
                that.setData({
                  upArr,
                  images: imgArr
                })
              }
            }
          })
        })
      }
    })
  },
  // 删除照片
  imgDelete(e) {
    let that = this
    let imgs = that.data.images,
      index = e.currentTarget.dataset.index;
    imgs.splice(index, 1)
    wx.showModal({
      title: '提示',
      content: '是否删除该图片',
      success(res) {
        if (res.confirm) {
          that.setData({
            images: imgs
          })
        }
      }
    })
  },
  // 找师傅表单提交
  submitRelease(e) {
    console.log(e)
    const regPhone = /^1[23456789]\d{9}$/;
    if (!e.detail.value.phone) {
      app.$tip('请输入手机号码')
      return
    }
    if (!regPhone.test(e.detail.value.phone)) {
      app.$tip('手机号格式不正确')
      return
    }
    if (!e.detail.value.introduce) {
      app.$tip('请填写描述')
      return
    }
    if (this.data.place == '请选择位置') {
      app.$tip('请选择位置')
      return;
    }
    wx.showLoading({
      title: '加载中...',
    })
    workRelease({
      token: wx.getStorageSync('token'),
      mobile: e.detail.value.phone,
      content: e.detail.value.introduce,
      work_cate_id: this.data.id,
      images: this.data.upArr.join(','),
      address: this.data.place,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude //纬度
    }).then(res => {
      app.$tip(res.msg)
      if (res.code == 1) {
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.chkLocation) {
      this.setData({
        place: app.globalData.detailedDddress,    //地址
        longitude: app.globalData.longitude,      //经度
        latitude: app.globalData.latitude         //纬度
      })
    }
    this.setData({
      id: options.id
    })
    this.getTypeWork(options.id)
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})